package com.liang.liuj.wallpaper.fragment;

import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;

import com.liang.liuj.wallpaper.R;

/**
 * 偏好设置的碎片页
 */
public class SettingFragment extends PreferenceFragment
        implements Preference.OnPreferenceChangeListener {

    public SettingFragment() {
        // Required empty public constructor
    }

    public static SettingFragment newInstance() {
        return new SettingFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref_main);
        setHasOptionsMenu(true);

        bindPreferenceSummaryToValue(findPreference(getString(R.string.key_update_interval)));
        bindPreferenceSummaryToValue(findPreference(getString(R.string.key_wait_deadline)));
    }

    private void bindPreferenceSummaryToValue(Preference preference) {
        // Set the listener to watch for value changes.
        preference.setOnPreferenceChangeListener(this);

        // Trigger the listener immediately with the preference's
        // current value.
        onPreferenceChange(preference,PreferenceManager
                        .getDefaultSharedPreferences(preference.getContext())
                        .getString(preference.getKey(), ""));
    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        String strValue = newValue.toString();
        if(preference instanceof ListPreference){
            ListPreference listPreference = (ListPreference) preference;
            int index = listPreference.findIndexOfValue(strValue);
            String summary = "";
            switch (preference.getKey()){
                case "update_interval":
                    summary = getString(R.string.string_update_interval_summary)+":";
                    break;
                case "wait_deadline":
                    summary = getString(R.string.string_wait_deadline_summary)+":";
                    break;
            }
            if(index>=0)
                summary += listPreference.getEntries()[index];
            else
                summary += "未选择";
            preference.setSummary(summary);
        }
        return true;
    }
}
